package cx.zan.dao;

import cx.zan.domain.User;
import cx.zan.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/3/30 19:06
 */
public class UserDao {
    /**
     * 注册功能保存用户
     * @param user
     * @return
     * @throws SQLException
     */
    public int saveUser(User user) throws SQLException {
        //注入数据源
        QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "insert into user values(?,?,?,?,?,?,?,?)";
        //private String uid;//用户id
        //private String username;
        //private String password;
        //private String name;
        //private String email;
        //private Date birthday;
        //private String gender;
        //private int state;       //激活状态  0未激活 1已激活
        //private String code;    //激活码
        //private String remark;
        int i = queryRunner.update(sql, user.getUid(), user.getUsername(), user.getPassword(), user.getName(),
                user.getEmail(), user.getBirthday(), user.getGender(), user.getRemark());
        return i;
    }

    /**
     * 登录功能
     * @param username
     * @param password
     * @return
     */
    public User login(String username,String password) {
        //注入数据源
        QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "select * from user where username = ? and password = ?";

        try {
            // 查询bean 时使用
            User user = queryRunner.query(sql, new BeanHandler<>(User.class),username,password);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }
}
